package sisi.categories;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.ListaStandardWindow;
import sisi.SimpleListModelSISI;


/**
 * CategoriesWindow.java - Controller class for <i>Categories window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 05/11/2013
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class CategoriesWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose, ListaStandardWindow {
	
	// listbox boxCategories
	private Window windowCategories, windowEditCategory;
	private Textbox tbCerca;
	private Listbox boxCategories;

	private List tutte_le_categorie;
	private boolean lNuovo;
	private Toolbarbutton buttonSeleziona;

	private ListModelList listModelList;
	private Integer idSelezionato = 0;

	protected Map<String, Object> args;
	private Object categoryItem;
	private Category modCategorie;
	// edit
	private Intbox id;
	private Textbox description;
	private Combobox categoryname;

	public void onCreate$windowCategories(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N"
				: tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		tutte_le_categorie = new CategoriesController().getCategoryList(null);
		listModelList.addAll(tutte_le_categorie);
		boxCategories.setModel(listModelList);
		boxCategories.setItemRenderer(new CategoriesItemRenderer());
		
		if (idSelezionato!=null && idSelezionato!=0){
			for (int i = 0; i < tutte_le_categorie.size(); i++) {
				Category categ = (Category)tutte_le_categorie.get(i);
				if (categ.getCategoryid()==idSelezionato.intValue()){
					boxCategories.setSelectedIndex(i);
					break;
				}
			}
		}

	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}
	
	public void onClick$buttonCerca(Event event) {
		cerca();
	}
	
	
	private void cerca(){
		listModelList = new ListModelList();
		tutte_le_categorie = new CategoriesController().getCategoryList(tbCerca
				.getValue());
		listModelList.addAll(tutte_le_categorie);
		boxCategories.setModel(listModelList);
		boxCategories.setItemRenderer(new CategoriesItemRenderer());		
	}
	
	
	
	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}
	
	
	public void onClick$buttonSeleziona(Event event) {

		seleziona();

	}

	public void seleziona() {
		if (boxCategories.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oCategory = boxCategories.getSelectedItem().getAttribute(
					"rigaCategory");
			String codiceSelezionato = ""+((Category) oCategory).getCategoryid();
			Sessions.getCurrent().setAttribute("codiceCategorySelezionato",
					codiceSelezionato);
			windowCategories.detach();
		}
	}


	@Override
	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	@Override
	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}
	
	private void modifica(boolean nuovo){
		try {

			int nIndex = boxCategories.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a Category to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxCategories", boxCategories);
				Window finestraEditCategory = (Window) Executions.createComponents(
						"/editCategory.zul", null, map);
				finestraEditCategory.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void onClick$buttonCancella(Event event) {
		// TODO Auto-generated method stub
		
	}	

	public class CategoriesItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Category) data).getCategoryid()).setParent(li);
			new Listcell(((Category) data).getCategoryname()).setParent(li);
			new Listcell(((Category) data).getDescription()).setParent(li);
			li.setAttribute("rigaCategory", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}

	
	
	// EDIT CATEGORY: NEW/MODIFY
	public void onCreate$windowEditCategory(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		boxCategories = (Listbox) args.get("boxCategories");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}
		
		ListModel listaCateg = new SimpleListModelSISI( new CategoriesController().getCategoryListOnlyName() );
		categoryname.setModel(listaCateg);
		
		if (!lNuovo) {
			categoryItem = boxCategories.getSelectedItem().getAttribute("rigaCategory");
			modCategorie = new CategoriesController()
					.refreshCategory((Category) categoryItem); 
			categoryItem = modCategorie;
			windowEditCategory.setTitle("Edit Category");
			categoryname.setFocus(true);
			id.setValue(modCategorie.getCategoryid());
			categoryname.setValue(General.toUpperAncheNull(modCategorie.getCategoryname()));
			description.setValue(General.toUpperAncheNull(modCategorie.getDescription()));
		} else {
			windowEditCategory.setTitle("New Category");
			categoryname.setFocus(true);
		}

	}
	
	public void onClick$btnAnnulla(Event event){
		windowEditCategory.detach();
	}
	
	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modCategorie = new Category();
		} else {

		}
		String testoMsg = "";
		
		modCategorie.setCategoryid(id.getValue());
		modCategorie.setCategoryname(General.toUpperAncheNull(categoryname.getValue()));
		modCategorie.setDescription(General.toUpperAncheNull(description.getValue()));
		
		if (lNuovo){
			new CategoriesController().addCategory(modCategorie);
			testoMsg = "Adding Category: "+ General.trimNull( modCategorie.getCategoryname() );
		} else {
			new CategoriesController().updateCategory(modCategorie);
			testoMsg = "Updating Category: "+ General.trimNull( modCategorie.getCategoryname() );			
		}
		
		General.showNotify( testoMsg, windowEditCategory);		
		
		windowEditCategory.detach();
		
		// aggiorna listbox
		
		if (lNuovo){
			ListModelList lml = (ListModelList) boxCategories.getListModel();
			lml.add(modCategorie);
			boxCategories.setSelectedIndex(lml.indexOf(modCategorie));
		} else {
			ListModelList lml = (ListModelList) boxCategories.getListModel();
			Object oCategoryItem = boxCategories.getSelectedItem().getAttribute("rigaCategory");
			if (lml.indexOf(oCategoryItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oCategoryItem), modCategorie);
			}
		}		
	}
	
	
}
